package com.leyantech.ecp.agenx.session.manager.handler;

import static com.leyantech.ecp.agenx.common.config.ConfigManager.ASSISTANT_EVENT_TOPIC;
import static com.leyantech.ecp.agenx.session.manager.handler.AssistantConfigHandler.toAssistant;

import com.leyantech.chaos.kafka.KafkaProducerStringClient;
import com.leyantech.ecp.agenx.common.config.EnumAssistantStatus;
import com.leyantech.ecp.agenx.common.redis.RedissonOperation;
import com.leyantech.ecp.agenx.common.redis.entity.OnlineAssistantSession;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-12-06.
 */
@Slf4j
@Singleton
public class AssistantStatusConfigHandler implements ConfigHandler {

  private final KafkaProducerStringClient producer;

  @Inject
  public AssistantStatusConfigHandler(KafkaProducerStringClient producer) {
    this.producer = producer;
  }

  @Override
  public String configName() {
    return "ASSISTANT_CONFIG";
  }

  @Override
  public void handle(JsonObject jsonObject) {
    final String sid = jsonObject.getString("sid");
    final String aid = jsonObject.getString("aid");
    final long timestamp = jsonObject.getLong("ts");

    final String assistantStatus = jsonObject.getString("assistantStatus");

    if (Arrays.stream(EnumAssistantStatus.values())
        .map(EnumAssistantStatus::name)
        .noneMatch(name -> name.equalsIgnoreCase(assistantStatus))) {
      log.error("unknown assistantStatus {}", assistantStatus);
      return;
    }

    final OnlineAssistantSession onlineAssistant = RedissonOperation.STORE_ASSISTANT
        .executor(sid)
        .get(map -> map.computeIfPresent(aid, (ignore, existValue) -> {
              existValue.setAction("CONFIG_CHANGED");
              existValue.setStatus(assistantStatus);
              existValue.setTimestamp(timestamp);
              return existValue;
            }
        ), "assistantStatusChange");

    if (onlineAssistant != null) {
      final String key = String.join(".", sid, aid);
      producer.send(ASSISTANT_EVENT_TOPIC.get(), key, toAssistant(onlineAssistant).toString());
    }

  }

}
